// pages/student/research/detail/detail.js
const app = getApp();

Page({
  data: {
    research: null,
    loading: true,
  },

  onLoad(options) {
    const { id } = options;
    if (id) {
      this.loadResearchDetail(id);
    } else {
      wx.showToast({
        title: "参数错误",
        icon: "error",
      });
      setTimeout(() => wx.navigateBack(), 1500);
    }
  },

  async loadResearchDetail(id) {
    try {
      const local = require("../../../../utils/local");
      const result = local.getResearchList();

      if (result.success) {
        const research = result.data.list.find((item) => item.id === id);
        if (research) {
          this.setData({
            research: research,
            loading: false,
          });
        } else {
          wx.showToast({
            title: "科研成果不存在",
            icon: "error",
          });
          setTimeout(() => wx.navigateBack(), 1500);
        }
      } else {
        throw new Error(result.message || "加载失败");
      }
    } catch (error) {
      console.error("加载科研成果详情失败:", error);
      wx.showToast({
        title: "加载失败",
        icon: "error",
      });
      this.setData({ loading: false });
    }
  },

  editResearch() {
    const { research } = this.data;
    if (research) {
      wx.navigateTo({
        url: `/pages/student/research/edit/edit?id=${research.id}`,
      });
    }
  },

  deleteResearch() {
    const { research } = this.data;
    if (!research) return;

    wx.showModal({
      title: "确认删除",
      content: "删除后无法恢复，确认删除这个科研成果吗？",
      success: (res) => {
        if (res.confirm) {
          this.doDeleteResearch(research.id);
        }
      },
    });
  },

  async doDeleteResearch(id) {
    wx.showLoading({ title: "删除中..." });

    try {
      const local = require("../../../../utils/local");
      const result = local.deleteResearch(id);
      if (result.success) {
        wx.showToast({
          title: "删除成功",
          icon: "success",
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: result.message || "删除失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("删除科研成果失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "error",
      });
    } finally {
      wx.hideLoading();
    }
  },

  previewFile(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url],
      current: url,
    });
  },

  // 阻止事件冒泡
  stopPropagation(e) {
    if (e && typeof e.stopPropagation === "function") {
      e.stopPropagation();
    }
  },
});
